package com.unionftech.content_login.ui.forget

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.Paint
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.view.ViewTreeObserver
import android.widget.TextView
import androidx.viewpager2.widget.ViewPager2
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator
import com.unionftech.common.R.drawable
import com.unionftech.common.R.string
import com.unionftech.common.base.BaseFragment
import com.unionftech.common.base.IUpdate
import com.unionftech.common.base.mvp.annitation.InjectPresenter
import com.unionftech.common.base.mvp.impl.BaseMvpActivity
import com.unionftech.common.bean.ApiException
import com.unionftech.common.bean.ResponseResult
import com.unionftech.common.bean.toast
import com.unionftech.common.bean.toastTimeout
import com.unionftech.common.common.language.DynamicResourceManager
import com.unionftech.common.recaptcha.RecaptchaUtil
import com.unionftech.common.utils.LogUtils
import com.unionftech.common.utils.SignUtils
import com.unionftech.common.utils.StatusBarUtil
import com.unionftech.common.utils.ToastUtils
import com.unionftech.content_login.R
import com.unionftech.common.common.adapter.CommonFragmentStateAdapter
import com.unionftech.common.common.bean.CountryInfo
import com.unionftech.content_login.bean.request.ForgetPasswordRequest
import com.unionftech.content_login.contract.LoginContract
import com.unionftech.content_login.presenter.LoginPresenter
import com.unionftech.common.common.GlobalInfoManager
import com.unionftech.content_login.ui.login.UFLoginActivity

class UFForgetPasswordActivity : BaseMvpActivity(), LoginContract.IForgotView, IUpdate {

    private val mTvHaveAccount by lazy { mRootView.findViewById<TextView>(R.id.tv_have_account) }
    private val mTvForgetPasswordTitle: TextView by lazy { mRootView.findViewById(R.id.tv_forget_password_title) }
    private val mTvGotoLogin: TextView by lazy { mRootView.findViewById(R.id.tv_goto_login) }
    private val mTabLayout: TabLayout by lazy { mRootView.findViewById(R.id.tab_layout) }
    private val mViewPager: ViewPager2 by lazy { mRootView.findViewById(R.id.view_pager) }
    private lateinit var mFragments: List<BaseFragment>
    private lateinit var mTitles: List<String>
    private lateinit var mAdapter: CommonFragmentStateAdapter
    private lateinit var mEmailForgetPasswordFragment: EmailForgetPasswordFragment
    private lateinit var mPhoneForgetPasswordFragment: PhoneForgetPasswordFragment
    private var mPublicKeyStr: String = ""
    private var mInitIndex = 1
    private var mObserver: ViewTreeObserver.OnGlobalLayoutListener? = null
    private var mCurRequest: ForgetPasswordRequest? = null

    @InjectPresenter
    private lateinit var mLoginPresenter: LoginPresenter

    companion object {
        private const val TAG = "UFForgetPasswordActivity"
        private const val PARAMS_INIT_INDEX = "PARAMS_INIT_INDEX"

        @JvmStatic
        fun startThis(context: Context) {
            val intent = Intent(context, UFForgetPasswordActivity::class.java)
            if (context !is Activity) {
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            }
            context.startActivity(intent)
        }

        @JvmStatic
        fun startThis(context: Context, initIndex: Int) {
            val intent = Intent(context, UFForgetPasswordActivity::class.java)
            if (context !is Activity) {
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            }
            intent.putExtra(PARAMS_INIT_INDEX, initIndex)
            context.startActivity(intent)
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    }

    override fun obtainIntentData(intent: Intent) {
        super.obtainIntentData(intent)
        mInitIndex = intent.getIntExtra(PARAMS_INIT_INDEX, 0)
    }

    override fun initLayout() = R.layout.activity_ufforget_password

    override fun statusBar() {
        StatusBarUtil.immersive(this)
        StatusBarUtil.setNavbarColor(
            this, mContext.getColor(com.unionftech.common.R.color.color_white)
        )
        StatusBarUtil.darkMode(this, false)
    }

    override fun initData() {
        super.initData()
        mEmailForgetPasswordFragment = EmailForgetPasswordFragment.newInstance()
        mPhoneForgetPasswordFragment = PhoneForgetPasswordFragment.newInstance()
        mFragments = listOf(mEmailForgetPasswordFragment, mPhoneForgetPasswordFragment)
        mTitles = listOf(
            DynamicResourceManager.getString(mContext, string.email),
            DynamicResourceManager.getString(mContext, string.phone)
        )
        mAdapter = CommonFragmentStateAdapter(this)
        mAdapter.addFragment(mFragments)
    }

    override fun initLanguageText() {
        super.initLanguageText()
        mTvForgetPasswordTitle.text =
            DynamicResourceManager.getString(mContext, string.forget_password_title)
        mTvGotoLogin.text = DynamicResourceManager.getString(mContext, string.log_in)
        mTvHaveAccount.text =
            DynamicResourceManager.getString(mContext, string.already_have_account)
    }

    override fun setListener() {
        super.setListener()
        mEmailForgetPasswordFragment.setRequestListener(::requestForgetPassword)
        mPhoneForgetPasswordFragment.setRequestListener(::requestForgetPassword)
        mTvGotoLogin.setOnClickListener(this)
        mObserver = ViewTreeObserver.OnGlobalLayoutListener {
            mViewPager.viewTreeObserver.removeOnGlobalLayoutListener(mObserver)
            mViewPager.setCurrentItem(mInitIndex, false)
            getPublicKey()
            getCountryInfoByIp()
        }
        mViewPager.viewTreeObserver.addOnGlobalLayoutListener(mObserver)
    }


    override fun setView() {
        super.setView()
        initTitleBar()
        mViewPager.adapter = mAdapter
        mViewPager.offscreenPageLimit = 1
        val textPaint = mTvGotoLogin.paint
        textPaint.flags = Paint.UNDERLINE_TEXT_FLAG //下划线
        textPaint.isAntiAlias = true //抗锯齿
        TabLayoutMediator(mTabLayout, mViewPager) { tab, position ->
            tab.text = mTitles[position]
        }.attach()
        loadData()
    }

    private fun initTitleBar() {
        hideCenterTitle()
        showBackImg(drawable.ic_title_back_white)
        mRootView.setBackgroundResource(R.drawable.ic_login_bg)
        setRightImg(drawable.ic_headphones_white) {
            //TODO:正在开发
            ToastUtils.longToast(
                DynamicResourceManager.getString(
                    mContext, string.developing
                )
            )
        }
    }

    override fun loadData() {
        super.loadData()
    }

    private fun getCountryInfoByIp() {
        val countryInfo = GlobalInfoManager.getInstance().getCountryInfo()
        if (countryInfo != null) {
            updateCountryInfoByIp(countryInfo)
        } else {
            GlobalInfoManager.getInstance().addListener(this)
            GlobalInfoManager.getInstance().update(GlobalInfoManager.UPDATE_COUNTRY_INFO)
        }
    }

    private fun getPublicKey() {
        val publicKeyStr = GlobalInfoManager.getInstance().getPublicKeyStr()
        if (!TextUtils.isEmpty(publicKeyStr)) {
            mPublicKeyStr = publicKeyStr
        } else {
            GlobalInfoManager.getInstance().addListener(this)
            GlobalInfoManager.getInstance().update(GlobalInfoManager.UPDATE_PUBLIC_KEY)
        }
    }

    override fun doClick(v: View?) {
        super.doClick(v)
        when (v?.id) {
            R.id.tv_goto_login -> UFLoginActivity.startThis(mActivity)
        }
    }

    private fun requestForgetPassword(request: ForgetPasswordRequest) {
        SignUtils.encrypt(
            SignUtils.loadPublicKeyByStr(mPublicKeyStr), request.encryptPassword.toByteArray()
        )?.also {
            val result = request.copy(
                encryptPassword = it
            )
            mCurRequest = request
            mLoginPresenter.resetPassword(result)
        }
    }

    override fun onUpdate(obj: Any?) {
        when (obj) {
            is String -> {
                mPublicKeyStr = obj
            }

            is CountryInfo -> {
                updateCountryInfoByIp(obj)
            }
        }
    }

    private fun updateCountryInfoByIp(countryInfo: CountryInfo) {
        if (::mEmailForgetPasswordFragment.isInitialized) {
            mEmailForgetPasswordFragment.setCountryInfo(countryInfo)
        }
        if (::mPhoneForgetPasswordFragment.isInitialized) {
            mPhoneForgetPasswordFragment.setCountryInfo(countryInfo)
        }
    }

    override fun handleResult(response: ResponseResult<Any?>) {
        if (response.code == ResponseResult.SUCCESS_CODE) {
            ToastUtils.longToast(
                DynamicResourceManager.getString(
                    mContext, string.reset_password_success
                )
            )
            mEmailForgetPasswordFragment.resetData()
            mPhoneForgetPasswordFragment.resetData()
            mCurRequest?.also {
                if (!TextUtils.isEmpty(it.loginEmail)) {
                    //跳转邮箱登录
                    UFLoginActivity.startThis(mActivity, it.loginEmail!!)
                } else {
                    val countryInfo = mPhoneForgetPasswordFragment.getCountryInfo()
                    UFLoginActivity.startThis(mActivity, countryInfo, it.loginPhone!!)
                }
            }

        } else {
            LogUtils.e(TAG, "handleResult error code:${response.code} msg:${response.msg}")
            if (ApiException.isTimeout(response.code)) {
                response.toastTimeout()
            } else {
                response.toast()
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        mAdapter.getFragment(mViewPager.currentItem)
            ?.onActivityResult(requestCode, resultCode, data)
    }

    override fun onDestroy() {
        GlobalInfoManager.getInstance().remove(this)
        RecaptchaUtil.getInstance().destroy()
        super.onDestroy()
    }


}